package com.google.collabframework.texteditor.model;

import java.util.ArrayList;
import java.util.StringTokenizer;

/**
 *
 * @author robert
 */
public class Document {

    private ArrayList<ArrayList<TextNode>> lines;
    private String text;

    public Document() {
        lines = new ArrayList<ArrayList<TextNode>>();
    }

    public Document(String text) {
        this();
        StringTokenizer to = new StringTokenizer(text, "\n");
        int i = 0;
        int lineCount = to.countTokens();
        while (i < lineCount) {
            lines.add(new ArrayList<TextNode>());
            ArrayList<TextNode> line = lines.get(i);
            char[] l = to.nextToken().toCharArray();
            for (char c : l) {
                line.add(new TextNode(c));
            }
            i++;
        }
    }

    public ArrayList<TextNode> getLine(int lineNumber) {
        return (lineNumber < lines.size()) ? lines.get(lineNumber) : null;
    }

    public char getChar(int line, int column) {
        ArrayList<TextNode> l = getLine(line);
        if (l == null) {
            return ' ';
        }
        return l.get(column).value;
    }

    public int getSize(int line) {
        return (lines.get(line) != null) ? lines.get(line).size() : 0;
    }

    public int getLineCount() {
        return lines.size();
    }

    public void add(int line, int column, char c) {
        lines.get(line).add(column, new TextNode(c));
    }

    public void remove(int line, int column) {
        lines.get(line).remove(column);
    }

    public String toString() {
        String text = "";
        for (ArrayList<TextNode> l : lines) {
            for (TextNode t : l) {
                text += t.value;
            }
            text += "\n";
        }
        return text;
    }

    public static void main(String[] args) {
        Document d = new Document("ich bin ein toller hecht,\nund weiß dass ich was drauf habe.");
        d.add(1, 12, 'ä');
        System.out.println(d.toString());
        d.remove(1, 12);
        System.out.println(d.toString());
    }
}
